<template>
  <BasicModal :width="1500" v-bind="$attrs" :title="getTitle"
    :canFullscreen="false" :centered="true" :destroyOnClose="true" :showCancelBtn="false" :showOkBtn="false"
    :bodyStyle="{height:'calc(100vh - 150px)', overflow:'hidden'}"
    @register="registerModal"
  >
  <split splitHeight="calc(100vh-5px)" leftWidth="900" style="overflow: hidden">
    <template #paneL>
      <BasicTable  @register="registerTable" 
        :onRowClick="handleClick" :onRowDbClick="handleDblclick" :rowClassName="rowClassName" :loading="loading"
      >
        <template #diffFmt="{text, record}">
          <span v-if="record?.hasDiff === 0">
            <a-icon type="check-circle" style="color: red" />
          </span>
          <span v-if="record?.hasDiff === 1">
            <a-icon type="close-circle" style="color: green" />
          </span>
          <span v-if="record?.hasDiff === 2">
            <a-icon type="close-circle" style="color: blue" />
          </span>
        </template>
      </BasicTable>
    </template>
    <template #paneR>
      <div class="jeecg-basic-table jeecg-basic-table-form-container" style="margin: 12px 0px 0 0; padding:0; padding-right: 10px;" :style="{height:'calc(100vh - 165px)', overflowY:'auto'}">
      <!-- 一、数据对比 - 银行流水 & 系统流水 2025-10-25 qindl---->
      <table class="orderTable" id="buctable">
        <tbody>
        <tr class="listBg">
          <th width="40"></th>
          <th width="130" class="text-center">银行收支流水</th>
          <th width="130" class="text-center">系统收支流水</th>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">编号</td>
          <td class="text-left" @dblclick="handleBankTempEditor(bankRunning.id)">{{bankRunning.id || '流水未导入'}}</td>
          <td class="text-left" @dblclick="handleBankRunningEditor(account.id)">{{account.id}}</td>
        </tr>
        <tr>
          <td class="bg-green-50">部门</td>
          <td class="text-left">{{ bankRunning.ddlx }}</td>
          <td class="text-left">{{ renderDict(account.ddlx, 'ddlxType') }}</td>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">订单</td>
          <td class="text-left">{{bankRunning.orderId}}</td>
          <td class="text-left">{{account.orderId}}</td>
        </tr>
        <tr>
          <td class="bg-green-50">收入</td>
          <td class="text-left text-green-600">
            <span>{{renderMoney(bankRunning.srje)}}</span>
          </td>
          <td class="text-left text-green-600">
            <span>{{renderMoney(account.srje)}}</span>
            <span class="bg-red-500 text-white rounded-full w-20px h-15px float-right flex items-center justify-center" style="font-size: 11px;" v-if="account.xnsz == 1">虚</span>
          </td>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">支出</td>
          <td class="text-left text-purple-600">
            <span>{{renderMoney(bankRunning.zcje)}}</span>
          </td>
          <td class="text-left text-purple-600">
            <span>{{renderMoney(account.zcje)}}</span>
            <span class="bg-red-500 text-white rounded-full w-18px h-15px float-right flex items-center justify-center" style="font-size: 11px;" v-if="account.xnsz == 1">虚</span>
          </td>
        </tr>
        <tr>
          <td class="bg-green-50">对方</td>
          <td class="text-left">{{bankRunning.dfzh}}</td>
          <td class="text-left">{{account.dfzh}}</td>
        </tr>
        <tr  class="listBg">
          <td class="bg-green-50">状态</td>
          <td class="text-left">---</td>
          <td class="text-left" :class="renderStatus(account.shbj, 'color')">{{ renderStatus(account.shbj, 'text') }} </td>
        </tr>
        <tr>
          <td class="bg-green-50">方式</td>
          <td class="text-left">---</td>
          <td class="text-left">{{account.sffsZw}}</td>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">录入</td>
          <td class="text-left">{{bankRunning.lrsj}}</td>
          <td class="text-left">{{account.lrsj}}</td>
        </tr>
        <tr>
          <td class="bg-green-50">审核</td>
          <td class="text-left">--</td>
          <td class="text-left">{{account.gxsj}}</td>
        </tr>
        <tr  class="listBg">
          <td class="bg-green-50">备注</td>
          <td class="text-left">{{bankRunning.bz}}</td>
          <td class="text-left">{{account.bz}}</td>
        </tr>
        </tbody>
      </table>

      <!--二、账务审核 2025-10-27 qindl---->
      <table class="orderTable" id="accounttable" v-if="accountFlowList?.optionList != null && accountFlowList?.optionList.length > 0">
        <thead><tr> <th colspan="12"> 账务审核 - {{ accountFlowList.title }}</th> </tr></thead>
        <tbody>
          <tr class="listBg">
            <th width="40"></th>
            <th width="60">部门</th>
            <th >订单编号</th>
            <th width="90" class="text-right">
              {{ accountFlowList.sflx == '1'? '收入' : '支出' }}
            </th>
            <th width="90">审核时间</th>
            <th width="80">审核人</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in accountFlowList.optionList" :key="index">
          <tr :class="index % 2 == 0 ? 'listBg' : 'cor'">
            <td>{{ index + 1 }}</td>
            <td>{{ list.ddlxZw }}</td>
            <a-popover title="备注" trigger="click">
            <template #content>
              <p style="width: 300px">{{ list.bz }}</p>
            </template>
            <td class="text-left truncate max-w-180px">{{ list.orderId }}</td>
            </a-popover>
            <td class="text-right text-green-500" v-if="list.sflx == '1'">{{ formatAmount(list.skje) }}</td>
            <td class="text-right text-purple-500" v-if="list.sflx == '2'">{{ formatAmount(list.fkje) }}</td>
            <td>{{ dateFormat(list.spsj, '') }}</td>
            <td>{{ list.sprName }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td class="tips text-right fwb text-green-500" v-if="accountFlowList.sflx == '1'">{{ formatAmount(accountFlowList.sumskje) }}</td>
            <td class="tips text-right fwb text-purple-500" v-if="accountFlowList.sflx == '2'">{{ formatAmount(accountFlowList.sumfkje) }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>

      <!--二、订单管理 - 收支项目 2025-08-25 qindl---->
      <table class="orderTable" id="accounttable" v-if="accountList?.optionList">
        <thead><tr> <th colspan="12"> 订单管理 - 收支项目 </th> </tr></thead>
        <tbody>
          <tr class="listBg">
            <th width="40"></th>
            <th width="60">部门</th>
            <th >收付名称</th>
            <th width="90" class="text-right">支出</th>
            <th width="90">审核时间</th>
            <th width="80">审核人</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in accountList.optionList" :key="index">
          <tr :class="index % 2 == 0 ? 'listBg' : 'cor'">
            <td>{{ index + 1 }}</td>
            <td>{{ list.ddlxZw }}</td>
            <a-popover title="备注" trigger="click">
            <template #content>
              <p style="width: 300px">{{ list.bz }}</p>
            </template>
            <td class="text-left truncate max-w-180px">{{ list.sflx == '1' ? list.customerPathName : list.cooperatorPathName }}</td>
            </a-popover>
            <td class="text-right text-green-500" v-if="list.sflx == '1'">{{ formatAmount(list.skje) }}</td>
            <td class="text-right text-purple-500" v-if="list.sflx == '2'">{{ formatAmount(list.fkje) }}</td>
            <td>{{ dateFormat(list.shsj, '') }}</td>
            <td>{{ list.shrName }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td class="tips text-right fwb text-green-500" v-if="accountList.sflx == '1'">{{ formatAmount(accountList.sumskje) }}</td>
            <td class="tips text-right fwb text-purple-500" v-if="accountList.sflx == '2'">{{ formatAmount(accountList.sumfkje) }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>

      <!--三、银行流水 - 系统流水 2025-09-18 qindl---->
      <table class="orderTable" id="accounttable" v-if="bankRunningList?.optionList != null && bankRunningList?.optionList.length > 0">
        <thead><tr> <th colspan="12"> 银行数据 - 系统流水 </th> </tr></thead>
        <tbody>
          <tr class="listBg">
            <th width="40"></th>
            <th width="60">部门</th>
            <th>订单编号</th>
            <th width="90" class="text-right" v-if="bankRunningList.sumsflx == '1'">收入</th>
            <th width="90" class="text-right" v-if="bankRunningList.sumsflx == '2'">支出</th>
            <th width="90">审核时间</th>
            <th width="80">审核人</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in bankRunningList.optionList" :key="index">
          <tr :class="index % 2 == 0 ? 'listBg' : 'cor'">
            <td>{{ index + 1 }}</td>
            <td>{{ list.ddlxZw }}</td>
            <a-popover title="备注" trigger="click">
            <template #content>
              <p style="width: 300px">{{ list.bz }}</p>
            </template>
            <td class="text-left truncate max-w-180px">{{ list.orderId }}</td>
            </a-popover>
            <td class="text-right text-green-500" v-if="list.sflx == '1'">{{ formatAmount(list.skje) }}</td>
            <td class="text-right text-purple-500" v-if="list.sflx == '2'">{{ formatAmount(list.fkje) }}</td>
            <td>{{ dateFormat(list.shsj, '') }}</td>
            <td>{{ list.shrName }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td>&nbsp;</td>
            <td class="tips text-right fwb text-green-500" v-if="bankRunningList.sumsflx == '1'">{{ formatAmount(bankRunningList.sumskje) }}</td>
            <td class="tips text-right fwb text-purple-500" v-if="bankRunningList.sumsflx == '2'">{{ formatAmount(bankRunningList.sumfkje) }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>

      </div>
    </template>
  </split>

  </BasicModal>

  <BankBalanceRealModal @register="registerBankBalanceRealModal"></BankBalanceRealModal>
  <BankBalanceTempModal @register="registerBankBalanceTempModal"></BankBalanceTempModal>

</template>

<script lang="ts" name="BankBalanceModal" setup>
  import {ref, toRaw, unref, reactive} from 'vue';
  import {BasicModal, useModalInner, useModal} from '/@/components/Modal';
  import {BasicTable, TableAction, ActionItem, BasicColumn, useTable} from '/@/components/Table';
  import {findBalanceDayReal, findBalanceDataReal} from "/@/views/full/bank/types/bank.api";
  import {useListPage} from '/@/hooks/system/useListPage';
  import {dateFormat, filterObj, formatAmount} from '/@/utils/common/compUtils';
  import {render} from '/@/utils/common/renderUtils';
  import BankBalanceRealModal from "/@/views/full/bank/modules/BankBalanceRealModal.vue";
  import BankBalanceTempModal from "/@/views/full/bank/modules/BankBalanceTempModal.vue";
  import Split from '/@/components/pt/split/Index.vue'
  import moment from 'dayjs';

  //----------定义变量 开始-------------------------------------------------------------
  const queryParam  = reactive<any>({});
  //标题
  const getTitle    = ref<any>('');
  const bankRunning = reactive<any>({});
  const account     = reactive<any>({});
  const accountList = reactive<any>([]);
  const bankRunningList = reactive<any>([]);
  const accountFlowList = reactive<any>([]);

  //----------定义变量 结束-------------------------------------------------------------

  // 初始化
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    //console.log('BankBalanceCheck@@@@@useModalInner', data);
    let record = data?.record || {};
    getTitle.value       = record?.title + " __ 收支日期：" + moment(record?.beginDate).format("YYYY-MM-DD") ;
    queryParam.bankId    = record?.bankId;
    queryParam.beginDate = record?.beginDate;
    queryParam.insider   = "";
    searchQuery();
  });

  const lsstatFmt = ({ text, record }) => {
    if (text && text !== '合计') {
      let color ='red';
      if (text == '0') {
        color = 'red';
      } else if (text == '1') {
        color ='green';
      } else {
        color ='blue';
      }
      return render.renderTag(record.diffField, color);
    }
  };

  const shbjFmt = ({ text }: { text: any }) => {
    if (text && text !== '合计') {
      const value = text == '0' ? '未审' : text == '1' ? '已审' : '未知';
      const color = text == '0' ? 'green' : text == '1' ? 'red' : 'blue';
      return render.renderTag(value, color);
    }
  };

  // 收付方式翻译
  const sffsFmt = ({ text, record }) => {
    if (!text) {
      return ''
    }
    let color : String[] = ['', 'red', '', 'blue', 'purple', 'orange'];
    return render.renderTag(render.renderDict(text, 'sffsType'), color[text])
  };

  // 金额格式化
  const moneyFmt = ({ text, record }) => {
    let color = 'red';
    if (text > 0) {
      color = 'text-green-600';
    } else if (text < 0) {
      color ='text-purple-600';
    } else {
      color ='text-blue-600';
    }
    return render.renderColor(formatAmount(text), color);
  };

  // --------------右边--列表----------------------------------------
  // 订单列表 - 表头
  const columns: BasicColumn[] = [
    { title: '部门', align: 'center', dataIndex: 'lsddlx', width: 60, customRender: ({ text, record }) => {
        if (record.xtsffs == '3') {
          return '挂账';
        } else {
          return render.renderDict(text, 'ddlxType');
        }
      } 
    },
    { title: '收支日期', align: 'center', dataIndex: 'jzrq', width: 85 },
    { title: '银行审核', align: 'center', dataIndex: 'lsstat', width: 60, customRender: lsstatFmt, },
    { title: '银行收支', align: 'right', dataIndex: 'lslrje', width: 90, customRender: moneyFmt },
    { title: '系统审核', align: 'center', dataIndex: 'xtstat', width: 60, customRender: shbjFmt, },
    { title: '系统方式', align: 'center', dataIndex: 'xtsffs', width: 60, customRender: sffsFmt, },
    { title: '系统收支', align: 'right', dataIndex: 'xtlrje', width: 90, customRender: moneyFmt },
    { title: '对账差额', align: 'right', dataIndex: 'lrce', width: 90, className: 'text-rose-600', customRender: ({text}) => formatAmount(text) },
    { title: '对账结果', align: 'center', dataIndex: 'diffField', width: 60, slots: { customRender: 'diffFmt' },}
  ];

  // 列表页面公共参数、方法
  const loading = ref<boolean>(false);
  const { prefixCls, tableContext } = useListPage({
    designScope: 'bankBalance-check',
    tableProps: {
      rowKey: "id",
      size: "small",
      api: findBalanceDayReal,
      columns: columns,
      showTableSetting: false,
      showIndexColumn: true, //行号
      showActionColumn: false,
      useSearchForm: false,
      resizeHeightOffset: 70,
      pagination: false,
      showSummary: true,
      immediate: false,
      summaryFunc: handleSummary,
      afterFetch: (res) => {
        if (res.length <= 0) {
          return
        }
        handleClick(res[0]);
      }
    }
  });

  //注册table数据
  const [registerTable, { reload, setProps, getRawDataSource, redoHeight }] = tableContext;

  // --------------右边--列表----------------------------------------

  // --------------组件--事件----------------------------------------
  //单击行
  let selectRows = reactive<any>({ id: '', lsid: '' , xtid: '', diffField: '' });
  function handleClick(record) {
    selectRows.id   = record.id;
    selectRows.lsid = record.lsid;
    selectRows.xtid = record.xtid;
    selectRows.diffField = record.diffField;
    loadBalanceDataReal()
  }

  //双击行
  function handleDblclick(record) {
    //handleEdit();
  }

  function rowClassName(record, index) {
    return record.id === selectRows.id ? 'row-selected' : '';
  }

  /**
   * 查询
   */
  function searchQuery() {
    let params = toRaw(filterObj(queryParam));
    setProps({ searchInfo: params });
    reload();
  }

  /**
   * 合计
   */
  function handleSummary(tableData: Recordable[]) {
    const res = getRawDataSource()
    redoHeight();
    if (res) {
      return getRawDataSource().summary;
    } else {
      return [];
    }
  }

  function loadBalanceDataReal() {
    // 优化：使用 Object.keys() 和 forEach 清空对象属性，提高性能
    const clearObject = (obj: any) => {
      Object.keys(obj).forEach(key => {
        delete obj[key];
      });
    };
  
    // 批量清空所有响应式对象
    [bankRunning, account, accountList, bankRunningList, accountFlowList].forEach(clearObject);
  
    // 参数验证
    if (!selectRows.lsid && !selectRows.xtid) {
      console.warn('loadBalanceDataReal: 缺少必要的参数 lsid 或 xtid');
      return;
    }
  
    let params = {
      lsid: selectRows.lsid,
      xtid: selectRows.xtid,
    };
  
    // 添加加载状态
    loading.value = true;
  
    findBalanceDataReal(params).then(res => {
      if (res.success) {
        // 优化：使用 Object.assign 批量赋值，减少重复代码
        const { 
          bankRunning: bankData, 
          account: accountData, 
          accountList: accountListData, 
          bankRunningList: bankRunningListData, 
          accountFlowList: accountFlowListData 
        } = res.result;
        
        // 批量更新数据
        Object.assign(bankRunning, bankData || {});
        Object.assign(account, accountData || {});
        Object.assign(accountList, accountListData || {});
        Object.assign(bankRunningList, bankRunningListData || {});
        Object.assign(accountFlowList, accountFlowListData || {});
  
        // 设置默认值
        if (!bankRunning.id) {
          bankRunning.id = '流水未导入';
        }
        if (!account.id) {
          account.id = '系统未审核';
        }
      } else {
        console.error('loadBalanceDataReal: API 调用失败', res.message);
        // 可以添加用户友好的错误提示
      }
    }).catch(error => {
      console.error('loadBalanceDataReal: 网络错误', error);
      // 可以添加网络错误的处理逻辑
    }).finally(() => {
      loading.value = false;
    });
  }

  function renderDict(text, code) {
    const value = render.renderDictText(text, code);
    return value;
    //return render.renderTag(value, 'text-blue-500');
  }

  function renderMoney(amount) {
    if (amount) {
      return formatAmount(amount);
    } else {
      return "";
    }
  }

  function renderStatus(text, type) {
    if (text == null || text === undefined || text === '' || text === '合计') {
      return text || '';
    }
    try {
      const color = text == '0' ? 'text-green-500' : text == '1' ? 'text-red-500' : 'text-green-500';
      const value = text == '0' ? '未审' : text == '1' ? '已审' : '未审';
      if (type == 'color') {
        return color;
      } else {
        return value;
      }
    } catch (error) {
      console.error('Error in statusFmt:', error);
      return text || '';
    }
  }
  // --------------组件--事件----------------------------------------

  //五、对账组件------------------------
  /**
   * 银行流水
   */
  const [registerBankBalanceTempModal, {openModal: openBankBalanceTempEditor}] = useModal();
  function handleBankTempEditor(id) {
    if (!id) {
      return
    }

    let params = {
      lsid: id
    }
    openBankBalanceTempEditor(true, { record: {...params}, isUpdate: true });
  }

  /**
   * 系统流水
   */
  const [registerBankBalanceRealModal, {openModal: openBankBalanceRealEditor}] = useModal();
  function handleBankRunningEditor(id) {
    let params = {
      xtid: id
    }

    openBankBalanceRealEditor(true, { record: {...params}, isUpdate: true });
  }

  //五、对账组件------------------------
</script>

<style lang="less" scoped>
  .orderTable th, .orderTable td  {
    height: 38px;
  }
</style>